﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace TCL.FUNC
{
    public class XmlEx
    {
        public static Object Xml2ListObject(string xml, System.Type type = null)
        {
            System.Xml.Serialization.XmlSerializer ser = default(System.Xml.Serialization.XmlSerializer);
            ser = new System.Xml.Serialization.XmlSerializer(type);
            System.IO.StringReader stream = new System.IO.StringReader(xml);
            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(stream);
            object a = ser.Deserialize(reader);
            return a;
        }

        public static String ListObject2Xml<T>(List<T> obj, string link_filename) where T : class
        {
            if (!String.IsNullOrEmpty(link_filename))
            {
                StreamWriter objStreamWriter = new StreamWriter(link_filename);
                XmlSerializer x = new XmlSerializer(obj.GetType());
                x.Serialize(objStreamWriter, obj);
                objStreamWriter.Close();
            }
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, obj);
            writer.ToString();
            return writer.ToString();
        }

        public static String Object2Xml<T>(T obj, string link_filename) where T : class
        {
            if (!String.IsNullOrEmpty(link_filename))
            {
                StreamWriter objStreamWriter = new StreamWriter(link_filename);
                XmlSerializer x = new XmlSerializer(obj.GetType());
                x.Serialize(objStreamWriter, obj);
                objStreamWriter.Close();
            }
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, obj);
            writer.ToString();
            return writer.ToString();
        }

        public static String ReplaceSpecialXMLCharater(string strInput)
        {
            strInput = strInput.Replace("&", "&amp;");
            strInput = strInput.Replace("<", "&lt;");
            strInput = strInput.Replace(">", "&gt;");
            strInput = strInput.Replace("\"", "&quot;");
            strInput = strInput.Replace("''", "&apos;");
            return strInput;
        }

        public static String RollbackSpecialXMLCharater(string strInput)
        {
            strInput = strInput.Replace("&amp;", "&");
            strInput = strInput.Replace("&lt;", "<");
            strInput = strInput.Replace("&gt;", ">");
            strInput = strInput.Replace("&quot;", "\"");
            strInput = strInput.Replace("&apos;", "''");
            return strInput;
        }
    }
}
